package org.bee.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

/**
 * 获取完整堆栈信息并以字符串的形式输出，方便日志打印
 */
public class ExceptionUtils {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionUtils.class);

    /**
     * 获取一个可抛出对象（Throwable）完整嵌套堆栈跟踪的一种方法。
     *
     * @param throwable 异常
     * @return 嵌套的堆栈跟踪，以字符串形式显示根本原因。
     */
    public static String getFullStackTrace(Throwable throwable) {
        String fullStackTrace = throwable.getLocalizedMessage();
        try (ByteArrayOutputStream byteStr = new ByteArrayOutputStream()) {
            throwable.printStackTrace(new PrintWriter(byteStr, true));
            fullStackTrace = byteStr.toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return fullStackTrace;
    }
}